package com.youi.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeepay.g3.sdk.yop.client.YopRequest;
import com.yeepay.g3.sdk.yop.client.YopResponse;
import com.yeepay.g3.sdk.yop.client.YopRsaClient;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.dao.MerchantDao;
import com.youi.entity.*;
import com.youi.exception.BusinessException;
import com.youi.model.FileInfo;
import com.youi.service.*;
import com.youi.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class MerchantServiceImpl extends BaseServiceImpl<Merchant> implements MerchantService {

	private final static String PRIVATEKEY="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCc8toUdxl3TEQDIMtCBqO4WTAuYptcAy38swCuBRl7BKEa3EHpgmO5SsoKMO45ObSNX03U4LnVHO4oTRug9LYWuIFCkOCM9EBq4CdV+SnWWhXP5ULkp4isp2z35YVYvVIiv+nN81jGakAFmjICtgkm71e9zSPo+usRpPtY7bQsBlRX1dQPPJZPso/0iAIg37iyTaJKWcNf2R0NEoCvAs34tW+URUyhMrfASpQ/bVTtHrW97118wRbXBq5i5RASH48+o60dlPuhHCTxLy+aZfK6RxrgTSrsQvxuhEiH0ObY4263MwU5unb9ect9P+zAY/Cy9GmPZglUTdhaLGbN7AApAgMBAAECggEAS5A84PeKgj5szFjAo5RQxNPj96EwDXfWb0C7hg0cfHb5HdaHwWYunypb5dYzC8g1no8RCPn9XpakLzEYqUDIXl4MlcDs69A5J3uuVJ02wGX09Hf74dyrV/zv4NZXgib8YZCmf6q2xiinlErt4xJDi8RWKSKYNHaCMKeO//zJ7xuHdsTwE9ei67Vn8TiqHT1O5I3ECGJ8QhGNYIEkysSQ4hzMz4vMu3e7vD41yhYh5043aMpmfiNSpK2VoNs/NQTG9NxmDaCWOqZIIRNonGmVrdKbLL6M+RU0iz9m82o8YfP3GnxiQ4NnlPGfjwvvEEOWTCaMcoHEdOoI6g3W1E34VQKBgQDYGDCloqKHu5GYxGAzWt56+bTglP1r3clQFFIX8aISbvFap4+x254co1rXOLd7LDlreCCX+uezb/1evwhZLeRSvShY+iA/KhVJD0CKMh5U1JkeaBAYJf/mZ3IzOSKFUHWeu042YhLIwOdeoiFboSurFAbVkGueoTeNQa6s5ai/9wKBgQC57o6tG4s2Iu3MMMJSy11FAgqXEEQzDvevKa/fK7lyU3dKJ0ZLpf3Tef8xq1B1Vt6hoxJvNZ4nlTcylz0kD/hylYbkD4pqiu7J1/0wEM7uIn6vfM8Ahb5OZ0uSnHQ+E30Y9bD1K63rQyRhR+g2+zD7S/RIcbcXuA57ScPwn1d43wKBgFVIzsJAOpcJLwA02KbMASxVqs5L3uyYXqBNNM0gX0+ZG4YkxXBzdaZlzi9MwhVJseu5QFva+WD3HO8sw9W2Z/tDjk33gYyMRlRMQbOI7jGaqke22Es/jAxZ3VdcAETPKWyZDdgmwrUadPYDVNj99ecSA1R8KA02IV+NgavZA82nAoGAKYDTvlZoo8P2Ot8jcWHNxwqmnIPYBWGw7hurE3DqK1fwR9Aug9Jgr2ULDuZDxn2GoqQJCGP6krFfKd7SmgsqlUFFZAEID7JFjS62aJVH66YtizSb7GzuRwgNuYNM+1JUWU72mjOO1fYd1806S5OUonOY6tbfXN8L9H9Jypt25hcCgYEAgBr1EnEdP9K7v92Itvws1+SGNPvfwYXoFzxwIXyT0dlnS5hvbunvWNyc2B4cGnN/fvErcvhuK3xnjM0gMtR0W6i/gcF2kO1nGI3SpQPSg1DnFbB0TI1WO8ACMQAN9/7CkfDo+JNOZ3ziTCXfHKJaPtUa57iHatA1cMjbNsFX0Gk=";

    private MerchantDao merchantDao;
    @Autowired
    private SysuserService sysuserService;
    @Autowired
    private MerchantimgsService merchantimgsService;
	@Autowired
	private MerchantcertService merchantcertService;
    @Autowired
    private MerchantbusinessService merchantbusinessService;
    @Autowired
    private MerchantsettlementService merchantsettlementService;
	@Autowired
	private ProvincecodeService provincecodeService;
	@Autowired
	private CitycodeService citycodeService;
	@Autowired
	private DistrictcodeService districtcodeService;
	@Autowired
	private BankcodeService bankcodeService;
    @Autowired
    public void setfaultRecordDao(MerchantDao merchantDao) {
        this.merchantDao = merchantDao;
        super.setBaseDAO(merchantDao);
    }

    @Override
    public void addMerchantSysuer(Long merchantId, String account, String password, Integer status) {
        // TODO Auto-generated method stub
        Sysuser sysuser = null;
        if (merchantId != null) {
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("account", account);
            sysuser = sysuserService.getByParam(prams);
            if (sysuser == null) {
                sysuser = new Sysuser(merchantId, account, MD5.getPwdMd5(password), status);
                sysuserService.saveOrUpdate(sysuser);
            }
        }
    }

    @Override
    public void getMerchantMsg(List<Merchant> merchantList) {
        // TODO Auto-generated method stub
        if (merchantList != null && merchantList.size() > 0) {
            for (Merchant merchant : merchantList) {
                Map<String, Object> prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put("merchantId", merchant.getId());
                List<Merchantimgs> merchantimgList = merchantimgsService.getByParams(prams);
                merchant.setMerchantimgList(merchantimgList);
            }
        }
    }

    @Override
    public void getMerchantMsg(Merchant merchant) {
        // TODO Auto-generated method stub
        if (merchant != null) {
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("merchantId", merchant.getId());
            List<Merchantimgs> merchantimgList = merchantimgsService.getByParams(prams);
            merchant.setMerchantimgList(merchantimgList);
        }
    }

    @Override
    public JSONObject enterMerchantToYibao(Long id) throws BusinessException, IOException {
        Merchant merchant = merchantDao.get(id);
        if (merchant == null) {
        	throw new BusinessException(CommonInfoUtil.NULLDATA, "商家信息不存在");
        }
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("merchantId", merchant.getId());
        Merchantbusiness merchantbusiness = merchantbusinessService.getByParam(prams);
        if (merchantbusiness == null) {
			throw new BusinessException(CommonInfoUtil.NULLDATA, "商家营业信息不存在");
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("merchantId", merchant.getId());
        Merchantsettlement merchantsettlement = merchantsettlementService.getByParam(prams);
        if (merchantsettlement == null) {
			throw new BusinessException(CommonInfoUtil.NULLDATA, "商家结算信息不存在");
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("merchantId", merchant.getId());
        Merchantcert merchantcert = merchantcertService.getByParam(prams);
        if (merchantcert == null) {
			throw new BusinessException(CommonInfoUtil.NULLDATA, "商家证件信息不存在");
        }
        if(merchantcert.getIdCardFront()==null || merchantcert.getIdCardFront().trim().length() == 0){
            throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少身份证正面");
        }
        if(merchantcert.getIdCareBehind()==null || merchantcert.getIdCareBehind().trim().length() == 0){
            throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少身份证反面");
        }
        if(merchantcert.getOpenaccountCert()==null || merchantcert.getOpenaccountCert().trim().length() == 0){
            throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少银行开户许可证");
        }
        if(merchantcert.getTaxCertificate()==null || merchantcert.getTaxCertificate().trim().length() == 0){
            throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少税务登记证");
        }
        if(merchantcert.getUsicCert()==null || merchantcert.getUsicCert().trim().length() == 0){
            throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少统一社会信息代码证");
        }
        if(merchantcert.getHandInCard()==null || merchantcert.getHandInCard().trim().length() == 0){
            throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少法人手持营业执照及身份证");
        }
        YopRequest yibaorequest = new YopRequest("OPR:" + "10033160799", PRIVATEKEY);
        yibaorequest.addParam("parentMerchantNo", "10033160799");
        //商户全称
        String merFullName = merchant.getName();
        if (merFullName == null || merFullName.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少商户全称");
        }
        yibaorequest.addParam("merFullName", merFullName);

        //商户简称
        String merShortName = merchant.getShortName();
        if (merShortName == null || merShortName.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少商户简称");
        }
        yibaorequest.addParam("merShortName", merShortName);

        //证件号
        String merCertNo = merchantbusiness.getScCode();
        if (merCertNo == null || merCertNo.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少证件号");
        }
        yibaorequest.addParam("merCertNo", merCertNo);

        //证件类型
        yibaorequest.addParam("merCertType", "UNI_CREDIT_CODE");

        //法人姓名
        String legalName = merchantbusiness.getContact();
        if (legalName == null || legalName.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少法人姓名");
        }
        yibaorequest.addParam("legalName", legalName);

        //法人身份证号
        String legalIdCard = merchantbusiness.getContactIdCard();
        if (legalIdCard == null || legalIdCard.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少法人身份证号");
        }
        yibaorequest.addParam("legalIdCard", legalIdCard);

        //商户联系人姓名
        String merContactName = merchant.getContacts();
        if (merContactName == null || merContactName.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少商户联系人姓名");
        }
        yibaorequest.addParam("merContactName", merContactName);

        //商户联系人手机号
        String merContactPhone = merchant.getPhone();
        if (merContactPhone == null || merContactPhone.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少商户联系人手机号");
        }
        yibaorequest.addParam("merContactPhone", merContactPhone);

        //商户联系人邮箱
        String merContactEmail = merchant.getEmail();
        if (merContactEmail == null || merContactEmail.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少商户邮箱");
        }
        yibaorequest.addParam("merContactEmail", merContactEmail);

        //商户省
        String merProvince = merchant.getProvince();
        if (merProvince == null || merProvince.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少商户省地址");
        }
        String provinceCode = provincecodeService.getProvincecodeByName(merProvince);
        if (provinceCode == null || provinceCode.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "没有省地址编码");
        }
        yibaorequest.addParam("merProvince", provinceCode);

        //商户市
        String merCity = merchant.getCity();
        if (merCity == null || merCity.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少商户市地址");
        }
        String cityCode = citycodeService.getCityCodeByCity(merCity);
        if (cityCode == null || cityCode.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "没有市地址编码");
        }
        yibaorequest.addParam("merCity", cityCode);
        String districtCode = districtcodeService.getDistrictcodeByCity(merCity);
        if (districtCode == null || districtCode.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "没有区地址编码");
        }
        yibaorequest.addParam("merDistrict", districtCode);

        //商户所在地址
        String merAddress = merchant.getAddress();
        if (merAddress == null || merAddress.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少商户所在地址");
        }
        yibaorequest.addParam("merAddress", merAddress);

        //税务登记证编号
        String taxRegistCert = merchantbusiness.getTaxCert();
        if (taxRegistCert == null || taxRegistCert.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少税务登记证编号");
        }
        yibaorequest.addParam("taxRegistCert", taxRegistCert);
        //开户许可证编号
        String accountLicense = merchantbusiness.getAolNo();
        if (accountLicense == null || accountLicense.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "开户许可证编号");
        }
        yibaorequest.addParam("accountLicense", accountLicense);
        //组织机构代码证
//			request.addParam("orgCode", "91350206MA31G7XL1G");
        //组织机构代理证有效期
//			request.addParam("orgCodeExpiry", "");
        //组织机构代码证是否长期有效
//			request.addParam("isOrgCodeLong", "");
        //结算银行账户
        String cardNo = merchantsettlement.getBankcardNo();
        if (cardNo == null || cardNo.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少结算银行账户卡号");
        }
        yibaorequest.addParam("cardNo", cardNo);
        //开户银行编码
        String headBank = merchantsettlement.getBank();
        if (headBank == null || headBank.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少开户银行总行");
        }
        String headBankCode = merchantsettlement.getBankCode();
        if (headBankCode == null || headBankCode.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "没有银行总行编码");
        }
        yibaorequest.addParam("headBankCode", headBankCode);
        //开户银行支行编码
        String bankBranch = merchantsettlement.getBranchCode();
        if (bankBranch == null || bankBranch.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少开户支行");
        }
        yibaorequest.addParam("bankCode", bankBranch);
        //开户省
        String bankProvince = merchantsettlement.getProvince();
        if (merProvince == null || merProvince.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少开户省地址");
        }
        String bankProvinceCode = provincecodeService.getProvincecodeByName(merProvince);
        if (bankProvinceCode == null || bankProvinceCode.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "没有省地址编码");
        }
        yibaorequest.addParam("bankProvince", bankProvinceCode);

        //开户市
        String bankCity = merchantsettlement.getCity();
        if (merCity == null || merCity.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "缺少商户市地址");
        }
        String bankCityCode = citycodeService.getCityCodeByCity(bankCity);
        if (bankCityCode == null || bankCityCode.trim().length() == 0) {
			throw new BusinessException(CommonInfoUtil.PARAMERROR, "没有市地址编码");
        }
        yibaorequest.addParam("bankCity", bankCityCode);
        //资质影印件
        List<FileInfo> fileInfoList = ObjectUtil.getFileInfo(merchantcert);
        String fileInfo = JsonUtil.toJson(fileInfoList);
        yibaorequest.addParam("fileInfo", fileInfo);
        //业务功能
        yibaorequest.addParam("businessFunction", "{\"SUBACCOUNT_IS_OPENED\": [\"YES\"]}");
        //入网请求号
        String requestNo = null;
        if (merchant.getRequestNo() != null) {
            requestNo = merchant.getRequestNo();
        } else {
            requestNo = MD5.getPwdMd5("MYJ" + new Date().getTime() + SmsUtil.getRandom(4));
        }
        yibaorequest.addParam("requestNo", requestNo);
        //商户回调地址
        yibaorequest.addParam("notifyUrl", "https://mp.myjjk.com.cn/MeiYiJiaHealth/checkEnterMerchant");
        YopResponse response = YopRsaClient.post("/rest/v1.0/sys/merchant/enterprisereginfoadd", yibaorequest);
        JSONObject data = null;
        if ("FAILURE".equals(response.getState())) {
            if (response.getError() != null)
                data = new JSONObject();
            data.put("code", response.getError().getCode());
            data.put("message", response.getError().getMessage());
        }
        if (response.getStringResult() != null) {
            Object object = JsonUtil.fromJson(response.getStringResult().toString(), Object.class);
            JSON json = (JSON) JSON.toJSON(object);
            data = JSONObject.parseObject(json.toJSONString());
            if (!data.getString("returnCode").equals("REG00000")) {
				throw new BusinessException(CommonInfoUtil.DATAERROR, data.getString("returnMsg"), data);
            }
            merchant.setMerchantNo(data.getString("merchantNo"));
            merchant.setRequestNo(data.getString("requestNo"));
            merchant.setYibaoStatus(1);
            merchantDao.saveOrUpdate(merchant);
        }
        return  data;
    }
}